/**
 * 工时查询页面
 */

'use client';

import React, { useState, useCallback } from 'react';
import { Layout, Space, Typography, message, Modal } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import Link from 'next/link';
import WorkloadQueryForm from '../../components/WorkloadQueryForm';
import WorkloadTable from '../../components/WorkloadTable';
import WorkloadStatistics from '../../components/WorkloadStatistics';
import { useWorkloads } from '../../hooks/useWorkloads';
import type { Workload, WorkloadQueryParams } from '../../types/workload';

const { Header, Content } = Layout;
const { Title } = Typography;

export default function WorkloadsPage() {
  const [queryParams, setQueryParams] = useState<WorkloadQueryParams>({
    page_index: 0,
    page_size: 30,
  });

  const { workloads, loading, total, statistics, fetchWorkloads } = useWorkloads();

  const handleSearch = useCallback((params: WorkloadQueryParams) => {
    console.log('搜索工时:', params);
    setQueryParams(params);
    fetchWorkloads(params);
  }, [fetchWorkloads]);

  const handlePageChange = useCallback((page: number, pageSize: number) => {
    const newParams = {
      ...queryParams,
      page_index: page - 1, // 转换为API使用的0-based索引
      page_size: pageSize,
    };
    setQueryParams(newParams);
    fetchWorkloads(newParams);
  }, [queryParams, fetchWorkloads]);

  const handleView = useCallback((workload: Workload) => {
    Modal.info({
      title: '工时详情',
      width: 800,
      content: (
        <div className="space-y-4">
          <div>
            <strong>工时ID:</strong> {workload.id}
          </div>
          <div>
            <strong>工时主体类型:</strong> {workload.principal_type}
          </div>
          <div>
            <strong>工时主体:</strong> {workload.principal.identifier} - {workload.principal.title}
          </div>
          <div>
            <strong>工时类型:</strong> {workload.type.name}
          </div>
          <div>
            <strong>工时时长:</strong> {workload.duration}小时
          </div>
          <div>
            <strong>审核状态:</strong> {workload.review_state}
          </div>
          {workload.description && (
            <div>
              <strong>工时描述:</strong> {workload.description}
            </div>
          )}
          <div>
            <strong>登记人:</strong> {workload.report_by.display_name}
          </div>
          <div>
            <strong>登记日期:</strong> {new Date(workload.report_at * 1000).toLocaleString()}
          </div>
          <div>
            <strong>创建时间:</strong> {new Date(workload.created_at * 1000).toLocaleString()}
          </div>
        </div>
      ),
    });
  }, []);

  const handleEdit = useCallback((workload: Workload) => {
    message.info('编辑功能待实现');
    console.log('编辑工时:', workload);
  }, []);

  const handleDelete = useCallback((workload: Workload) => {
    message.info('删除功能待实现');
    console.log('删除工时:', workload);
  }, []);

  const handleExport = useCallback((workloads: Workload[]) => {
    // 简单的CSV导出
    const headers = [
      'ID',
      '工时主体类型',
      '工时主体标识',
      '工时主体标题',
      '工时类型',
      '工时时长(小时)',
      '审核状态',
      '工时描述',
      '登记人',
      '登记日期',
      '创建时间'
    ];

    const csvContent = [
      headers.join(','),
      ...workloads.map(workload => [
        workload.id,
        workload.principal_type,
        workload.principal.identifier,
        `"${workload.principal.title.replace(/"/g, '""')}"`,
        workload.type.name,
        workload.duration,
        workload.review_state,
        `"${(workload.description || '').replace(/"/g, '""')}"`,
        workload.report_by.display_name,
        new Date(workload.report_at * 1000).toLocaleDateString(),
        new Date(workload.created_at * 1000).toLocaleString()
      ].join(','))
    ].join('\n');

    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `workloads_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    message.success(`已导出 ${workloads.length} 条工时记录`);
  }, []);

  return (
    <Layout className="min-h-screen bg-gray-50">
      <Header className="bg-white shadow-sm border-b px-6">
        <div className="flex items-center justify-between h-full">
          <Space size="large">
            <Link href="/" className="flex items-center text-gray-600 hover:text-blue-600">
              <ArrowLeftOutlined className="mr-2" />
              返回首页
            </Link>
            <Title level={3} className="!mb-0 !text-gray-800">
              工时查询
            </Title>
          </Space>
        </div>
      </Header>

      <Content className="p-6">
        <div className="max-w-full mx-auto space-y-6">
          {/* 查询表单 */}
          <WorkloadQueryForm
            onSearch={handleSearch}
            loading={loading}
            initialValues={queryParams}
          />

          {/* 工时统计 */}
          <WorkloadStatistics
            statistics={statistics}
            queryParams={queryParams}
            loading={loading}
          />

          {/* 工时表格 */}
          <WorkloadTable
            workloads={workloads}
            loading={loading}
            total={total}
            currentPage={(queryParams.page_index || 0) + 1} // 转换为1-based显示
            pageSize={queryParams.page_size || 30}
            onView={handleView}
            onEdit={handleEdit}
            onDelete={handleDelete}
            onExport={handleExport}
            onPageChange={handlePageChange}
          />
        </div>
      </Content>
    </Layout>
  );
}